<template>
  <div class="mobile-box">
    <div class="tabs-box">
      <div class="top">{{ pageTitle }}</div>
      <el-tabs v-model="active" @tab-click="handleClick">
        <el-tab-pane label="待审批" name="1"></el-tab-pane>
        <el-tab-pane label="已审批" name="2"></el-tab-pane>
        <el-tab-pane label="已完成" name="3"></el-tab-pane>
      </el-tabs>
    </div>

    <div class="list-box">
      <ul
        class="infinite-list"
        v-infinite-scroll="loadMore"
        style="overflow: auto"
        
        infinite-scroll-disabled="busy"
      >
        <li
          class="item infinite-list-item"
          v-for="(item, index) in approveApplyList"
          :key="index"
        >
          <ItemShow
            v-if="item.boxInfo && item.boxInfo[0] && item.boxInfo[0].boxTagList"
            :dataItem="item"
            @examine="examine"
            :active="active"
            :userId="userId"
          />
        </li>
      </ul>
     
      <div class="no-data" v-if="approveApplyList.length === 0">
        <img src="@/assets/images/mobile/nothing.png" alt="暂无记录" />
        <span>暂无记录！</span>
      </div>

      <div class="user-bottom">
        <div class="user">
          {{ userPhone }}
        </div>
        <div class="ge">|</div>
        <div class="out" @click="goOut">退出</div>
      </div>
    </div>

    <div class="fixed-bottom" v-if="active == 1 && approveApplyList.length > 0">
      <div class="approval-all" @click="approvalAll">全部批准</div>
    </div>

    <el-backtop target=".list-box" :bottom="50" :right="10">
      <i class="el-icon-caret-top"></i>
    </el-backtop>

    <SpecialDialog
      :title="dialogTitle"
      :visible="dialogVisible"
      @close="closeDialog"
      @confirm="examineSubmit"
    />
  </div>
</template>

<script>
import {
  getOrderList,
  getOrderListCount,
  getOrderBoxList,
  approveAllReadOrder,
  approveReadOrder,
  cancelReadOrder,
} from "@/api/access-manage/index";
import { userLogout } from "@/api/member/index";
import { getTaglistByUserBoxIds } from "@/api/access-manage/index";

import ItemShow from "./components/ItemShow";
import SpecialDialog from "./components/SpecialDialog";
export default {
  name: "mobileApproval",
  components: { ItemShow, SpecialDialog },
  computed: {},
  data() {
    return {
      userPhone: "",
      userId: "",
      active: "1",
      orderType: 0,
      orderName: "调阅",
      orderStatus: 0,
      pendingStatus: 1,
      approveApplyList: [],
      pageSize: 5,
      pageNum: 1,
      total: 0,

      dialogTitle: "",
      dialogVisible: false,
      examineType: "",
      examineOrderId: "",

      busy: false,
      pageTitle: ''
    };
  },
  created() {
    this.orderType = this.getTypeRelyRoute();
    this.getApprovalOrderList();
  },
  mounted() {
    setTimeout(()=> {
      this.userPhone = JSON.parse(
        localStorage.getItem("localUserInfo")
      ).mobile;
      this.userId = JSON.parse(localStorage.getItem("localUserInfo")).id;
    }, 1000)
  },
  methods: {
    //   加载更多
    loadMore() {
      this.busy = true;
      if (this.total > 0 && this.total === this.approveApplyList.length) return 
      this.pageNum = this.pageNum + 1;
      this.getMoreList();
    },
    //  待审批 列表 - 加载更多
    getMoreList() {
      let data = {
        type: this.orderType,
        status: this.orderStatus,
        pending: this.pendingStatus,
      };
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      new Promise((resolve) => {
        getOrderList(data, params)
          .then((res) => {

            res.data.map((e) => {
              e.createdOn = this.$moment(e.createdOn * 1000).format(
                "YYYY-MM-DD HH:mm:ss"
              );
              getOrderBoxList({orderId: e.id}, {pageSize: 5, pageNum: 1}).then((boxListRes) => {
                e.boxInfo = boxListRes.data;
                e.pageNum = 1
                e.boxTotal = boxListRes.total

                // 去查看当前订单中窍的标签
                if (e.boxInfo.length > 0) {
                  let ids = [];
                  e.boxInfo.map((item) => {
                    ids.push(item.userBoxId);
                  });

                  getTaglistByUserBoxIds(ids).then((tagRes) => {
                    e.boxInfo.map((item) => {
                      item["boxTagList"] = []
                      tagRes.data.map((tags) => {
                        if (tags.userBoxId == item.userBoxId) {
                          item["boxTagList"] = tags.tagList.filter(m => m.tag != ';' && m.tag != '；');
                        }
                      });
                    });
                    setTimeout(() => {
                      this.$forceUpdate();
                    }, 1000);
                  });
                }
              });
            });

            this.approveApplyList = this.approveApplyList.concat(res.data)
            // this.total = res.total;
            getOrderListCount(data, params).then(resm => {
              this.total = resm
            })
            setTimeout(() => {
              this.busy = false
            }, 1200);
          })
          .catch((err) => {
            this.busy = false
          });
      });
    },
    // 根据路由判断审批种类
    getTypeRelyRoute() {
      const name = this.$route.name;
      if (name == "BorrowApproval") {
        this.orderName = "调阅";
        this.pageTitle = '调阅审批'
        return 0;
      }
      if (name == "DestroyApproval") {
        this.orderName = "销毁";
        this.pageTitle = '销毁审批'
        return 2;
      }
      if (name == "OffShelfApproval") {
        this.orderName = "永久下架";
        this.pageTitle = '永久下架审批'
        return 3;
      }
    },
    // 获得 待审批 列表
    getApprovalOrderList() {
      let data = {
        type: this.orderType,
        status: this.orderStatus,
        pending: this.pendingStatus,
      };
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      // 加载框
      const loading = this.$loading({
        lock: true,
        text: "加载中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.5)",
      });

      new Promise((resolve) => {
        getOrderList(data, params)
          .then((res) => {
            this.approveApplyList = res.data;
            this.approveApplyList.map((e) => {
              e.createdOn = this.$moment(e.createdOn * 1000).format(
                "YYYY-MM-DD HH:mm:ss"
              );
              getOrderBoxList({orderId: e.id}, {pageSize: 5, pageNum: 1}).then((boxListRes) => {
                e.boxInfo = boxListRes.data;
                e.pageNum = 1
                e.boxTotal = boxListRes.total
                // 去查看当前订单中窍的标签
                if (e.boxInfo.length > 0) {
                  let ids = [];
                  e.boxInfo.map((item) => {
                    ids.push(item.userBoxId);
                  });

                  getTaglistByUserBoxIds(ids).then((tagRes) => {
                    e.boxInfo.map((item) => {
                      item["boxTagList"] = []
                      tagRes.data.map((tags) => {
                        if (tags.userBoxId == item.userBoxId) {
                          item["boxTagList"] = tags.tagList.filter(m => m.tag != ';' && m.tag != '；');
                        }
                      });
                    });
                    setTimeout(() => {
                      this.$forceUpdate();
                    }, 1000);
                  });
                }
              });
            });

            // this.total = res.total;
            getOrderListCount(data, params).then(resm => {
              this.total = resm
            })
            setTimeout(() => {
              loading.close();
            }, 2000);
          })
          .catch((err) => {
            loading.close();
          });
      });
    },
    // 重新加载列表
    getListAgain() {
      this.busy = false;
      this.pageSize = 5;
      this.pageNum = 1;

      this.getApprovalOrderList();
    },

    // tab 点击
    handleClick() {
      if (this.active == 1) {
        this.orderStatus = 0;
        this.pendingStatus = 1;
      } else if (this.active == 2) {
        this.orderStatus = 0;
        this.pendingStatus = 2;
      } else if (this.active == 3) {
        this.orderStatus = 2;
        this.pendingStatus = undefined;
      }
      this.getListAgain();
    },
    // 全部通过
    approvalAll() {
      this.dialogVisible = true;
      // examineType 3 全部通过
      this.examineType = 3;
      this.dialogTitle = "确定通过全部申请吗？";
    },
    // 审核
    examine(data) {
      // examineType 1 同意  2 取消
      this.examineType = data.examineType;
      this.examineOrderId = data.id;

      if (data.examineType === 2) {
        this.dialogTitle = "确定拒绝该申请吗？";
      } else if (data.examineType === 1) {
        this.dialogTitle = "确定通过该申请吗？";
      }
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
    },
    // 弹框确定
    examineSubmit() {
      this.dialogVisible = false;
      // 加载框
      const loading = this.$loading({
        lock: true,
        text: "加载中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.5)",
      });
      // 调用接口
      if (this.examineType === 1) {
        // 批准
        approveReadOrder({ id: this.examineOrderId, approvalType: 0 })
          .then((res) => {
            this.$message({
              type: "success",
              message: this.orderName + "已通过",
            });
            this.getListAgain();
          })
          .catch((err) => {
            this.getListAgain();
          });
      } else if (this.examineType === 2) {
        // 拒绝
        const data = {
          files: [],
          id: this.examineOrderId
        }

        cancelReadOrder(data)
          .then((res) => {
            this.$message({
              type: "success",
              message: this.orderName + "已驳回",
            });
            this.getListAgain();
          })
          .catch((err) => {
            this.getListAgain();
          });
      } else if (this.examineType === 3) {
        //  全部批准
        approveAllReadOrder({ type: this.orderType })
          .then((res) => {
            this.$message({
              type: "success",
              message: "全部待" + this.orderName + "审批通过",
            });
            this.getListAgain();
          })
          .catch((err) => {
            this.getListAgain();
          });
      }
    },
    // 退出
    goOut() {
      userLogout().then((res) => {
        this.$store.commit("app/REMOVE_USERINFO");
        this.$store.commit("app/CLEAR_LOCAL_USERINFO");
        localStorage.clear();

        this.$router.push({ path: "/mobileLogin" });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.mobile-box {
  width: 100%;
  height: 100%;
  .top {
    height: 50px;
    width: 100%;
    background-color: #f88123;
    line-height: 50px;
    color: #fff;
    text-align: center;
    font-size: 16px;
  }
  .tabs-box {
    position: fixed;
    top: 0;
    width: 100%;
    background-color: #fff;
  }

  .list-box {
    background-color: #f5f5f5;
    padding: 100px 0.1rem 50px;
    height: 100vh;
    overflow-x: hidden;
    .item {
      margin-bottom: 20px;
      padding: 0 10px;
    }

    .no-data {
      height: calc(100% - 50px);
      margin: 0 10px 20px;

      display: flex;
      flex-direction: column;
      // align-items: center;
      text-align: center;
      img {
        width: 100px;
        margin: 50px auto 20px;
      }
    }

    .user-bottom {
      display: flex;
      padding: 0 10px;
      margin-bottom: 10px;
      .ge {
        margin: 0 6px;
      }
      .out {
        color: #f88123;
      }
    }
  }
  .fixed-bottom {
    width: 100%;
    position: fixed;
    bottom: 0;
    background-color: #fff;
    .approval-all {
      line-height: 40px;
      background-color: #f88123;
      color: #fff;
      text-align: center;
    }
  }

  // 修改tab样式
  ::v-deep  .el-tabs__header {
    margin: 0;
    .el-tabs__nav {
      width: 100%;
      .el-tabs__item {
        width: 33.3%;
        text-align: center;
      }
    }
  }
}
</style>
